package com.nineshadow.games.entity;


import com.nineshadow.games.constants.CommonConstants;
import com.nineshadow.games.core.GameRoom;
import com.nineshadow.games.interfaces.IGameUser;
import com.nineshadow.games.launch.GameWorld;
import com.nineshadow.games.launch.HallServer;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import java.util.Objects;

/**
 * 轮询工具
 */
@Slf4j
public class PollHandler implements Runnable {
    //间隔时间ms
    private static int INTERVAL_TIME=300;

    private volatile boolean isDone;
    private Integer userId;
    public PollHandler(int userId) {
        this.userId=userId;
        GameWorld.USER_POLL_EXECUTOR_SERVICE.execute(this);
    }

    @Override
    public void run() {
        try {
            log.info("用户轮询开始：userId:{}---isDone:{}",userId,isDone);
            IGameUser gameUser=GameWorld.getOnlineUser(userId);
            while (!isDone) {
                sendMsg(gameUser);
                Thread.sleep(INTERVAL_TIME);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        log.info("用户轮询结束：userId:{}",userId);
        isDone = true;
    }

    public void sendMsg(IGameUser user) throws Exception {
        String key=CommonConstants.USER_POLL_QUEUE +user.getLastRoomId()+":"+ user.getUserId();
        Object msg = HallServer.redisUtil.lGet(key);
        if (Objects.nonNull(msg)) {
            JSONObject jsonObject = JSONObject.fromObject(msg);
            log.info("{}，----收到消息：{}", user.getUserId(), msg);
            String method = jsonObject.getString("method");
            Object sendMsg = null;
            if (jsonObject.containsKey("msg")) {
                sendMsg = jsonObject.getString("msg");
                if (Objects.nonNull(sendMsg)) {
                    JSONObject msgJson = JSONObject.fromObject(sendMsg);
                    sendMsg = msgJson;
                    isTerminated(method, msgJson);
                }
            }
            user.sendMsg(sendMsg, method);
        }
    }

    private void isTerminated(String method,JSONObject msgJson) {
        if(method.equals("gameOver")){
            GameRoom gameRoom=GameWorld.getRoom(msgJson.get("roomId").toString());
            if(Objects.nonNull(gameRoom)){
                gameRoom.terminate();
            }
        }
    }
    public boolean isDone() {
        return isDone;
    }

    public void setDone(boolean done) {
        isDone = done;
    }

}
